<?php

declare(strict_types=1);

namespace catcher\platform;

use think\App;
use think\facade\Log;
use catcher\Code;
use catchAdmin\order\model\OrdersTemp as OrdersTempModel;
use catcher\platform\order\OrderService;
use catcher\platform\order\Kaspi;

/**
 * Houzz 接口服务
 * Class KaspiService
 * Interface getOrders
 * @link https://guide.kaspi.kz/partner/ru/shop/api/orders/q3201
 */
class KaspiService extends BasePlatformService
{
    /**
     * 调用接口
     * @var mixed|string
     */
    protected $interface = 'orders';

    public function __construct($interface = '', $startDate = '', $minute = -1000)
    {
        $this->interface = $interface ?: $this->interface;
        parent::__construct($this->interface, $startDate, $minute);
    }
    /**
     * 店铺实例
     * @var
     */
    private static $shopInstance = [];

    /**
     * 获取订单列表
     * @param array $config
     * @param array $params 参数配置，默认抓取当天订单
     * @param bool $replace 是否替换原有的订单，默认不替换
     * @return bool
     * @date 2025/05/20
     */
    public function getOrderList($config = [], $params = [], $replace = false)
    {
        // 获取客户端
        $client = $this->getClient($config);
        // 总数量
        $count = 0;
        // 分页
        $nextCursor = 0;
        try {
            do {
                // 拉取销售订单列表数据
                $orderList = $client->getOrders(
                    $this->getGetAt($config['shopId'])->getTimestamp() * 1000,
                    $this->getNow()->getTimestamp() * 1000,
                    'APPROVED_BY_BANK',
                    $nextCursor
                );
                // 是否还有下一页
                if (($nextCursor+1) >= $orderList['meta']['pageCount']) {
                    $nextCursor = '';
                }
//            print_r($orderList);exit();
                $orderList = $orderList['data'] ?? [];
                // 检查是否有订单，当订单为一个时则重组数组
                foreach ($orderList as $order) {
                    // 拉取销售订单商品数据
                    $itemList = $client->getEntries($order['id']);
                    $order['items'] = $itemList;
                    // 原始订单全部数据预存储到订单临时表
                    if ($this->pushOrderToTemp(
                        $order['attributes']['code'],
                        $order,
                        ['id' => Code::KASPI, 'name' => $this->getPlatform()],
                        $config['shopId'],
                        false,
                        $order['id']
                    )) {
                        $count++;
                    }
                    $nextCursor++;
                }
            } while (!empty($nextCursor));
            // 写入接口调用记录
            return $this->saveGetOrderRecord($count, $config['shopId']);
        } catch (\Exception $e) {
            $message = sprintf(
                $this->getPlatform() . " 店铺【%d-%s】拉取订单，异常信息:【%s】",
                $config['shopId'],
                $config['shopName'],
                $e->getCode() . ':' . $e->getMessage() .
                    ' in ' . $e->getFile() . ' on line ' . $e->getLine()
            );
            Log::info($message);
            return $message;
        }
    }

    /**
     * 同步订单
     * @param OrdersTempModel $ordersTempModel
     * @return bool
     * @throws \Exception
     */
    public function syncOrder(OrdersTempModel $ordersTempModel)
    {
        $data = $ordersTempModel->order_info;
        $item = [];
        $buyer = null;
        $count = 0;
        if (isset($data['items']) && is_array($data['items'])) {
            foreach ($data['items']['data'] as $key => $info) {
                if (!isset($info['attributes']['offer']['code'])) {
                    continue;
                }
                $item[$key] = [
                    "item_id" => $info['id'], // 商品 id
                    "product_code" => $info['attributes']['offer']['code'], // 商品编码
                    "goods_id" => 0,
                    "quantity_purchased" => $info['attributes']['quantity'], // 数量
                    "transaction_price_currencyid" => 'KZT', //单位
                    "transaction_price_value" => $info['attributes']['basePrice'], // 售价
                    "tax_amount_currencyid" => 'KZT',
                    "tax_amount_value" => 0, // 税额
                    "sku" => $info['attributes']['offer']['code'], // sku
                    "name" => $info['attributes']['offer']['name'] ?? '', // 产品名称
                    "buyer_email" => '', // 邮箱
                    "buyer_user_firstname" => '', // 姓名
                    "buyer_user_lastname" => '',
                    "company_id" => 0,
                    "goods_type" => Code::TYPE_PRODUCT // 默認非組合商品
                ];
                // 累计商品数量
                $count += $info['attributes']['quantity'];
            }
        }
        // 客户收货信息
        $address = $data['attributes']['deliveryAddress'] ?? [];
        $buyer = [
            "address_name"              => $data['attributes']['customer']['name'] ?? '', // 收件人
            "address_phone"             => $data['attributes']['customer']['cellPhone'] ?? '', // 电话
            "address_email"             => '',
            "address_country_name"      => '', // 国家
            "address_country"           => '', // 国家编码
            "address_stateorprovince"   => '', // 买家所在省，州
            "address_cityname"          => $address['town'] ?? '', // 城市
            "address_postalcode"        => $address['streetNumber'] ?? '', // 邮编
            "address_street1"           => $address['streetName'] ?? '', // 买家收货地址1
            "address_street2"           => $address['apartment'] ?? '', // 买家收货地址2
            "address_street3"           => $address['formattedAddress'] ?? '', // 买家收货地址3
        ];
        // 订单基本信息
        $order = [
            "platform_no"               => $ordersTempModel->order_no,
            "platform_no_ext"           => $ordersTempModel->order_no2,
            "shop_basics_id"            => $ordersTempModel->shop_id,
            "platform"                  => $this->getPlatform(), // 平台名称
            "platform_id"               => Code::KASPI,
            "status"                    => Code::ORDER_UNSHIPPED, // 订单状态
            "get_at"                    => (new \DateTime($ordersTempModel->created_at))->getTimestamp(), // 订单在拉取的的时间
            "created_at"                => (int) ($data['attributes']['creationDate'] / 1000), // 订单在平台生成的时间
            "total_num"                 => $count,
            "total_price"               => $data['attributes']['totalPrice'], // 订单总金额
            "paid_at"                   => (int) ($data['attributes']['approvedByBankDate'] / 1000), // 订单支付时间
            "timezone"                  => '+08:00', // 时区
            "currency"                  => 'KZT', // 币种
            "shipping_code"             => '', // 运单号
            "shipping_method"           => $data['attributes']['deliveryMode'], // 运输方式
            "platform_remark"           => '', // 买家备注信息
            "order_type"                => Code::ORDER_TYPE_SALES,
            "order_source"              => Code::ORDER_SOURCE_API,
            "order_buyer"               => $buyer,
            "creator_id"                => 1, // 默认超级管理员
        ];

        // todo: refunds 是否存在退款信息
        return App(OrderService::class)->saveOrder($order, $item, 1, 0, false);
    }

    /**
     * 获取操作Kaspi的客户端
     * @param array $config 店铺秘钥配置
     * @return Kaspi
     * @date 2025/05/20
     */
    public function getClient($config = [])
    {
        $client = null;
        try {
            // 实例化客户端连接信息
            $client = new Kaspi($config['token']);
        } catch (\Exception $e) {
            $message = sprintf("%s Client，异常信息:【%s】", $this->getPlatform(), $e->getMessage());
            Log::info($message); // 记录实例化客户端异常
            throw new \Exception($message);
        }
        return $client;
    }

    /**
     * 根据数据库的内容同步店铺账号信息
     * @throws \Exception
     */
    public function setShop($shopId = 0)
    {
        // TODO: Implement setShop() method.
        $shops = $this->getShop(Code::KASPI, $shopId);
        $config = [];
        $message = [];
        foreach ($shops as $key => $shop) {
            $config['token'] = $shop['platform_parameters']['token'];
            $config['shopId'] = $shop['id'];
            $config['shopName'] = $shop['shop_name'];
            static::$shopInstance[$config['shopId']] = $config;
            // 循环调用拉取订单列表
            // 返回错误信息
            if (($res = $this->getOrderList($config)) !== 1) {
                $message[$key] = $res;
            }
        }
        // 抛出异常信息
        if (!empty($message)) {
            throw new \Exception(implode(',', $message));
        }
    }
}
